import _ from 'underscore'
import {Scope} from 'lib/scopeFactory'
import {coreApi} from '../apis/core-util'
import TimeStore from 'lib/stores/time-store'
import moment from 'moment'

import dispatcher from 'lib/dispatcher'

export default class DetailScope extends Scope {

  constructor(props) {
    super(props);

    this.nameId = props.routeParams.id;

    this.$state = {
      frameName: '--',
      frameLastTime: '--',
      frameCount: '--',

      list: {
        loading: true
      },
      listLimit: 10,
      listOffset: 0
    };

    this.titleApi = coreApi({
      size: 1,
      offset: 0,
      limit: 1,
      sm: 1,
      nameId: this.nameId,
      classify: 'measurementname',
      urlName: 'activitytracesimilar'
    }, TimeStore.getValue);

    this.listApi = coreApi({
      size: 1,
      order: 101,
      sm: 1,
      offset: () => this.$state.listOffset,
      limit: () => this.$state.listLimit,
      nameId: this.nameId,
      urlName: 'activitytracelist'
    }, TimeStore.getValue);
  }

  $load() {
    this.titleApi.fetch().done((json) => {
      if (json && json.result && json.result && json.result.length) {
        let item = json.result[0];

        this.$state.frameName = item.key.name;
        this.$state.frameCount = item.data[0].count;
        this.$state.frameLastTime = moment(item.data[0].lastTime).format('YYYY-MM-DD HH:mm:ss');
      }

      this.emit();
    }).fail((error) => {
      console.log(error);
    });

    this.listApi.fetch().done((json) => {
      this.$state.list = {
        data: json,
        hasMore: json.length === this.$state.listLimit
      };
      this.$state.listOffset += json.length;

      if (this.$state.list.hasMore) {
        this.$state.list.showMore = () => {
          let deferred = $.Deferred();
          this.listApi
              .fetch()
              .fail(deferred.reject)
              .done((innerJson) => {
                this.$state.listOffset += innerJson.length;
                deferred.resolve({
                  data: innerJson,
                  hasMore: this.$state.listLimit === innerJson.length
                });
              });

          return deferred.promise();
        };
      }

      this.emit();
    }).fail((error) => {
      console.log(error);
    });
  }
}
